﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace WindowsHelloWorldService
{
    public partial class UploadService : ServiceBase
    {
        Timer timer = new Timer(); // name space(using System.Timers;)  

        public UploadService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            WriteMessageToFile("Service started.");
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000; //number in milisecinds  
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            WriteMessageToFile("Service stopped.");
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            WriteMessageToFile("Service is called.");
        }

        public void WriteMessageToFile(string Message)
        {
            //var path = Path.GetFullPath($"ServiceLog_{DateTime.Now:yyyyMMdd}.txt");
            //using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
            //    sw.WriteLine($"{DateTime.Now:HH:mm:ss} {Message}");
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }

        //protected void OnStart1(string[] args)
        //{
        //    using (StreamWriter sw = new StreamWriter("", true, Encoding.UTF8))
        //    {
        //        sw.WriteLine($"{DateTime.Now:yyyy/MM/dd HH:mm:ss} Windows HelloWorld Service Started.");
        //    }
        //}

        //protected void OnStop1()
        //{
        //    using (StreamWriter sw = new StreamWriter("", true, Encoding.UTF8))
        //    {
        //        sw.WriteLine($"{DateTime.Now:yyyy/MM/dd HH:mm:ss} Windows HelloWorld Service Stopped.");
        //    }
        //}
    }
}
